<template>
    <el-container class="layout-container" v-loading="loading">
        <template v-if="!hasError && isInitialized">
            <!-- 遮罩层 -->
            <transition name="overlay" appear>
                <div v-if="isMobile && !isCollapse" class="drawer-overlay" @click="toggleAside"></div>
            </transition>

            <!-- 左侧菜单 -->
            <div style="padding: 4px;">
                <transition name="aside-slide" appear>
                    <el-aside class="aside-container" :class="['aside', { 'mobile-aside': isMobile }]"
                        :style="asideStyle">
                        <div class="logo-container">
                            <transition name="fade" appear>
                                <span class="platform-name" v-show="!isCollapse || isMobile">融禹</span>
                            </transition>
                        </div>
                        <transition name="nav-fade" appear>
                            <nav-list :is-collapse="isCollapse" :is-mobile="isMobile" />
                        </transition>
                    </el-aside>
                </transition>
            </div>

            <!-- 右侧内容区 -->
            <transition name="main-slide" appear>
                <el-container :class="['right-container', { 'mobile-right': isMobile }]" :style="mainContainerStyle">
                    <transition name="header-slide" appear>
                        <app-header :is-collapse="isCollapse" :is-mobile="isMobile" @update:is-collapse="updateCollapse"
                            @fullscreen-change="handleFullscreenChange" />
                    </transition>
                    <el-main class="main-content">
                        <div class="router-view-container">
                            <router-view v-slot="{ Component }">
                                <!-- 如果子组件有多个根节点，暂时移除过渡效果 -->
                                <div class="page-wrapper">
                                    <component :is="Component" />
                                </div>
                            </router-view>
                        </div>
                    </el-main>

                    <transition name="help-bounce" appear>
                        <HelpButton></HelpButton>
                    </transition>
                </el-container>
            </transition>
        </template>

        <!-- 错误界面 -->
        <transition name="error-zoom" appear>
            <el-result v-if="hasError" icon="error" :title="errorTitle" :sub-title="errorMessage" class="error-result">
                <template #extra>
                    <el-button type="primary" @click="initializeData">重试</el-button>
                </template>
            </el-result>
        </transition>

    </el-container>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import NavList from '@/components/nav/NavList.vue'
import AppHeader from '@/components/header/Header.vue'
import { useUserStore } from "@/stores/userinfo"
import { useCompanyStore } from "@/stores/company"
import { useAreaStore } from "@/stores/area"
import { handleError } from '@/utils/handleError'
import HelpButton from '../../components/help/HelpButton.vue'
// 状态变量
const isCollapse = ref(false)
const isMobile = ref(false)
const isFullscreen = ref(false)
const isInitialized = ref(false)
const hasError = ref(false)
const errorMessage = ref('')
const loading = ref(false) // 控制加载状态
const isTablet = ref(false)

// stores
const userStore = useUserStore()
const companyStore = useCompanyStore()
const areaStore = useAreaStore()

// 计算侧边栏样式
const asideStyle = computed(() => ({
    width: isMobile.value
        ? isCollapse.value ? '0' : '260px'
        : isTablet.value
            ? (isCollapse.value ? '3rem' : '240px')
            : (isCollapse.value ? '4rem' : '260px'),
    borderRadius: '8px'
}))

// 计算主容器样式
const mainContainerStyle = computed(() => ({
    marginLeft: isFullscreen.value ? '0' : 'auto'
}))

// 初始化数据
const initializeData = async () => {
    loading.value = true // 开始加载
    try {
        await userStore.getUserInfo()
        // 设置当前公司
        companyStore.setCurrentCompany(userStore.userCompany)
        // 并行加载其他数据
        await areaStore.fetchAreas(),
            isInitialized.value = true
        hasError.value = false
    } catch (error) {
        hasError.value = true
        if (error.code === 401) {
            errorMessage.value = '账号已过期，请重新登录'
        } else {
            errorMessage.value = '初始化数据失败,请刷新页面重试'
        }
        handleError(error, errorMessage.value, false, false)
    } finally {
        loading.value = false // 加载完成
    }
}

// 切换侧边栏
const toggleAside = () => {
    if (isMobile.value) {
        isCollapse.value = !isCollapse.value
    }
}

// 更新折叠状态
const updateCollapse = (value) => {
    isCollapse.value = value
}

// 检查是否为移动设备
const checkMobile = () => {
    const width = window.innerWidth
    const newIsMobile = width <= 768
    const newIsTablet = width > 768 && width <= 1024
    if (isMobile.value !== newIsMobile) {
        isMobile.value = newIsMobile
        isCollapse.value = newIsMobile
    }
    isTablet.value = newIsTablet
}

// 处理全屏变化
const handleFullscreenChange = (fullscreen) => {
    isFullscreen.value = fullscreen
}

// 网络状态处理
const isOnline = ref(navigator.onLine)

const updateNetworkStatus = () => {
    isOnline.value = navigator.onLine
    if (!isOnline.value) {
        hasError.value = true
        errorMessage.value = '网络连接不可用，请检查您的网络'
        ElNotification({
            type: 'warning',
            title: '网络警告',
            message: errorMessage.value,
            duration: 0,
            showClose: true
        })
    } else {
        hasError.value = false
        errorMessage.value = ''
        ElNotification.closeAll()
        // 尝试重新初始化数据
        initializeData()
    }
}
onMounted(async () => {
    checkMobile()
    window.addEventListener('resize', checkMobile)
    // 监听网络状态变化
    window.addEventListener('online', updateNetworkStatus)
    window.addEventListener('offline', updateNetworkStatus)
    // 初始化数据
    if (isOnline.value) {
        await initializeData()
    } else {
        hasError.value = true
        errorMessage.value = '网络连接不可用，请检查您的网络'
        ElNotification({
            type: 'warning',
            title: '网络警告',
            message: errorMessage.value,
            duration: 0,
            showClose: true
        })
    }
})
// Store handlers for removal
onUnmounted(() => {
    window.removeEventListener('resize', checkMobile)
    window.removeEventListener('online', updateNetworkStatus)
    window.removeEventListener('offline', updateNetworkStatus)
})
const errorTitle = computed(() => {
    return '发生错误'
})
</script>
<style scoped lang="scss">
.layout-container {
    height: 100vh;
    position: relative;
    background-color: var(--color-background);
}

.aside-container {
    background-image: url("../../assets/images/navlistbg.svg");
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

// 遮罩层样式
.drawer-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
    cursor: pointer;
}

.aside {
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    overflow: hidden;
    z-index: 1000;
    height: 100%;
    padding: 16px;

    &.mobile-aside {
        position: fixed;
        left: 0;
        top: 0;
        height: 100%;
        transform: translateX(0);
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
        transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);

        &[style*="width: 0"] {
            transform: translateX(-100%);
        }
    }

    .logo-container {
        color: #fff;
        font-size: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        margin-bottom: 16px;

        .logo {
            width: 40px;
            height: 40px;
            margin-right: 12px;
        }

        .platform-name {
            font-weight: 800;
            white-space: nowrap;
            transition: all 0.3s ease;
        }
    }
}

.right-container {
    height: 100vh;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    display: flex;
    flex-direction: column;

    &.mobile-right {
        margin-left: 0 !important;
    }
}

.main-content {
    flex: 1;
    overflow: auto;
}

.router-view-container {
    height: 100%;
    width: 100%;
}

.error-result {
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
}

.view-wrapper {
    height: 100%;
    width: 100%;
}

// 加载界面样式
.loading-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: var(--color-background);
    z-index: 1001;

    .loading-spinner {
        text-align: center;

        .spinner-ring {
            width: 60px;
            height: 60px;
            border: 4px solid rgba(59, 130, 246, 0.2);
            border-top: 4px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        .loading-text {
            color: #666;
            font-size: 16px;
            margin: 0;
            animation: pulse 2s ease-in-out infinite;
        }
    }
}

// 过渡动画样式
// 1. 遮罩层过渡
.overlay-enter-active,
.overlay-leave-active {
    transition: opacity 0.3s ease;
}

.overlay-enter-from,
.overlay-leave-to {
    opacity: 0;
}

// 2. 侧边栏滑动过渡
.aside-slide-enter-active,
.aside-slide-leave-active {
    transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.aside-slide-enter-from,
.aside-slide-leave-to {
    transform: translateX(-100%);
    opacity: 0;
}

// 3. 主内容区滑动过渡
.main-slide-enter-active,
.main-slide-leave-active {
    transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.main-slide-enter-from,
.main-slide-leave-to {
    transform: translateX(50px);
    opacity: 0;
}

// 4. 头部滑动过渡
.header-slide-enter-active,
.header-slide-leave-active {
    transition: all 0.3s ease;
    transition-delay: 0.1s;
}

.header-slide-enter-from,
.header-slide-leave-to {
    transform: translateY(-30px);
    opacity: 0;
}

// 页面包装器样式
.page-wrapper {
    height: 100%;
    width: 100%;
}

// 5. 页面切换过渡
.page-enter-active,
.page-leave-active {
    transition: all 0.3s ease;
}

.page-enter-from {
    opacity: 0;
    transform: translateX(30px);
}

.page-leave-to {
    opacity: 0;
    transform: translateX(-30px);
}

// 6. 帮助按钮弹跳过渡
.help-bounce-enter-active {
    transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
    transition-delay: 0.3s;
}

.help-bounce-enter-from {
    transform: scale(0) rotate(180deg);
    opacity: 0;
}

// 7. 错误页面缩放过渡
.error-zoom-enter-active,
.error-zoom-leave-active {
    transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.error-zoom-enter-from,
.error-zoom-leave-to {
    transform: scale(0.8);
    opacity: 0;
}

// 8. 加载页面淡入过渡
.loading-fade-enter-active,
.loading-fade-leave-active {
    transition: all 0.3s ease;
}

.loading-fade-enter-from,
.loading-fade-leave-to {
    opacity: 0;
}

// 9. 导航菜单淡入过渡
.nav-fade-enter-active,
.nav-fade-leave-active {
    transition: all 0.3s ease;
    transition-delay: 0.2s;
}

.nav-fade-enter-from,
.nav-fade-leave-to {
    opacity: 0;
    transform: translateY(20px);
}

// 10. 基础淡入过渡
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

// 动画关键帧
@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

@keyframes pulse {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }
}

// 响应式动画优化
@media (max-width: 768px) {

    .aside-slide-enter-active,
    .aside-slide-leave-active,
    .main-slide-enter-active,
    .main-slide-leave-active {
        transition-duration: 0.25s;
    }
}
</style>